﻿using System;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.SpatialAnalystTools;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;

namespace School
{
    public partial class DistanceSettingsForm : Form
    {
        private AxMapControl _mapControl;

        public DistanceSettingsForm(AxMapControl mapControl)
        {
            InitializeComponent();
            _mapControl = mapControl;
            Load += DistanceSettingsForm_Load;
        }

        private void DistanceSettingsForm_Load(object sender, EventArgs e)
        {
            cmbInputLayer.Items.Clear();
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                if (layer is IFeatureLayer)
                {
                    cmbInputLayer.Items.Add(layer.Name);
                }
            }
            if (cmbInputLayer.Items.Count > 0)
                cmbInputLayer.SelectedIndex = 0;
        }

        private void btnBrowseOutput_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Filter = "TIFF 栅格文件 (*.tif)|*.tif";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    txtOutputPath.Text = dlg.FileName;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                string selectedLayer = cmbInputLayer.SelectedItem?.ToString();
                string inputPath = GetLayerPath(selectedLayer);
                string outputPath = txtOutputPath.Text;

                if (string.IsNullOrEmpty(inputPath) || string.IsNullOrEmpty(outputPath))
                {
                    MessageBox.Show("请选择输入图层并设置输出路径。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取 DEM 图层（作为环境参数参考）
                string demPath = GetDEMRasterPath();
                if (string.IsNullOrEmpty(demPath))
                {
                    MessageBox.Show("未找到 DEM 图层，请添加并命名为“DEM”或“dem”。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                GeoProcessor gp = new GeoProcessor();
                gp.OverwriteOutput = true;

                // 设置环境参数：与 DEM 图层一致
                gp.SetEnvironmentValue("extent", demPath);
                gp.SetEnvironmentValue("cellsize", demPath);
                gp.SetEnvironmentValue("snapRaster", demPath);
                gp.SetEnvironmentValue("mask", demPath);

                // 设置工具参数（不设置 maximum_distance）
                EucDistance tool = new EucDistance
                {
                    in_source_data = inputPath,
                    out_distance_raster = outputPath
                };

                // 使用 IVariantArray 来传参
                IVariantArray parameters = new VarArrayClass();
                parameters.Add(tool.in_source_data);
                parameters.Add(tool.out_distance_raster);

                ITrackCancel trackCancel = new CancelTrackerClass();

                IGeoProcessorResult result = (IGeoProcessorResult)gp.Execute("EucDistance", parameters, trackCancel);

                if (result.Status == esriJobStatus.esriJobSucceeded)
                {
                    LoadRasterLayer(outputPath);
                    MessageBox.Show("欧氏距离分析完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("欧氏距离分析失败，请检查参数。", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetLayerPath(string layerName)
        {
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                if (layer is IFeatureLayer fl && layer.Name == layerName)
                {
                    IDataset dataset = fl.FeatureClass as IDataset;
                    return System.IO.Path.Combine(dataset.Workspace.PathName, dataset.Name);
                }
            }
            return null;
        }

        private string GetDEMRasterPath()
        {
            for (int i = 0; i < _mapControl.LayerCount; i++)
            {
                ILayer layer = _mapControl.get_Layer(i);
                if (layer is IRasterLayer rasterLayer &&
                    (rasterLayer.Name.Equals("高程", StringComparison.OrdinalIgnoreCase) ||
                     rasterLayer.Name.Equals("DEM", StringComparison.OrdinalIgnoreCase) ||
                     rasterLayer.Name.IndexOf("dem", StringComparison.OrdinalIgnoreCase) >= 0))
                {
                    IRaster raster = rasterLayer.Raster;
                    IRaster2 raster2 = raster as IRaster2;
                    if (raster2 != null)
                    {
                        IRasterDataset dataset = raster2.RasterDataset;
                        IDataset ds = dataset as IDataset;
                        return System.IO.Path.Combine(ds.Workspace.PathName, ds.Name);
                    }
                }
            }
            return null;
        }



        private void LoadRasterLayer(string rasterPath)
        {
            IRasterLayer rasterLayer = new RasterLayerClass();
            rasterLayer.CreateFromFilePath(rasterPath);
            rasterLayer.Name = "欧氏距离结果";
            _mapControl.AddLayer(rasterLayer);
            _mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
